package com.jihui.jihuipicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;

import com.jihui.jihuipicturebackend.model.dto.space.SpaceAddRequest;
import com.jihui.jihuipicturebackend.model.entity.Space;
import com.jihui.jihuipicturebackend.model.entity.SpaceUser;
import com.jihui.jihuipicturebackend.model.enums.SpaceLevelEnum;
import com.jihui.jihuipicturebackend.model.enums.SpaceRoleEnum;
import com.jihui.jihuipicturebackend.model.enums.SpaceTypeEnum;
import com.jihui.jihuipicturebackend.model.vo.SpaceVO;
import com.jihui.jihuipicturebackend.service.SpaceService;
import com.jihui.jihuipicturebackend.service.SpaceUserService;
import com.jihui.jihuipicturebackend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihui.jihuipicturebackend.constant.UserConstant;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.exception.ThrowUtils;
import com.jihui.jihuipicturebackend.mapper.SpaceMapper;
import com.jihui.jihuipicturebackend.model.dto.space.SpaceQueryRequest;
import com.jihui.jihuipicturebackend.model.dto.space.SpaceUpdateRequest;
import com.jihui.jihuipicturebackend.model.entity.User;
import com.jihui.jihuipicturebackend.model.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wu'ji'hui
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-02-09 13:59:12
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    @Resource
    UserService userService;

    @Resource
    SpaceUserService spaceUserService;

    @Resource
    TransactionTemplate transactionTemplate;


    /**
     * 创建空间
     *
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        // 1.填充参数默认值
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        Space space = new Space();
        BeanUtil.copyProperties(spaceAddRequest, space);
        // 填充空间级别
        fillSpaceBySpaceLevel(space);
        // 填充空间类型
        Integer spaceType = spaceAddRequest.getSpaceType();
        if (spaceType == null) {
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 2.校验参数
        validSpace(space, true);
        // 3.权限校验，非管理员只能创建普通级别的空间
        long userId = loginUser.getId();
        space.setUserId(userId);
        if (space.getSpaceLevel() != SpaceLevelEnum.COMMON.getValue()
                && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非管理员不能创建非普通级别的空间");
        }
        // 4.控制统一用户智能创建一个空间(针对用户进行加锁操作)
        String lock = String.valueOf(userId).intern();
        synchronized (lock) {
            Long spaceId = transactionTemplate.execute(status -> {
                boolean exists = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType, space.getSpaceType())
                        .exists();
                ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户仅能有一个私有空间");
                // 如果是团队空间，则需要将创建空间的用户加入到空间的成员中
                if (space.getSpaceType() == SpaceTypeEnum.TEAM.getValue()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    boolean result = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                // 写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 返回新写入的数据 id
                return space.getId();
            });
            // 返回结果是包装类，可以做一些处理
            return Optional.ofNullable(spaceId).orElse(-1L);
        }
    }


    /**
     * 通过id删除空间
     *
     * @param spaceId
     * @return
     */
    @Override
    public boolean deleteSpaceById(Long spaceId) {
        // 根据 id 查询空间是否存在
        Space space = this.getById(spaceId);
        ThrowUtils.throwIf(space == null,
                new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在"));
        // 删除空间
        ThrowUtils.throwIf(baseMapper.deleteById(spaceId) == 0,
                new BusinessException(ErrorCode.NOT_FOUND_ERROR, "删除失败"));
        return true;
    }

    /**
     * 获取空间 VO
     *
     * @param spaceUpdateRequest
     * @param loginUser
     * @return
     */
    @Override
    public SpaceVO updateSpace(SpaceUpdateRequest spaceUpdateRequest, User loginUser) {
        // 校验空间上传请求
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        long spaceId = spaceUpdateRequest.getId();
        // 更新本地数据库中的空间信息
        Space space = this.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        BeanUtil.copyProperties(spaceUpdateRequest, space);
        // 数据校验
        this.validSpace(space, false);
        // 自动填充数据
        this.fillSpaceBySpaceLevel(space);
        // 更新数据库
        boolean result = this.saveOrUpdate(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "空间跟新失败");
        return SpaceVO.objToVo(space);
    }

    /**
     * 构造查询条件
     *
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getSpaceQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (ObjUtil.isEmpty(spaceQueryRequest)) {
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取单个空间信息
     *
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public SpaceVO getSpaceVO(SpaceQueryRequest spaceQueryRequest) {
        // 对象转封装类
        Space space = baseMapper.selectOne(getSpaceQueryWrapper(spaceQueryRequest));
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 获取空间脱敏后的列表信息
     *
     * @param spacePage
     * @param httpServletRequest
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceListVO(Page<Space> spacePage, HttpServletRequest httpServletRequest) {
        List<Space> spaceRecords = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(),
                spacePage.getTotal());
        if (CollUtil.isEmpty(spaceRecords)) {
            return spaceVOPage;
        }
        // picture 转 pictureVO
        List<SpaceVO> pictureVOList = spaceRecords.stream().map(SpaceVO::objToVo).collect(Collectors.toList());

        // 补充用户信息
        // 1. 关联查询用户信息
        // 先从 space 中取出所有用户 id
        Set<Long> userIdSet = spaceRecords.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 再根据 id 集合查询所有用户信息
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            // 脱敏处理
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            pictureVO.setUser(userVO);
        });
        spaceVOPage.setRecords(pictureVOList);
        return spaceVOPage;
    }

    /**
     * 校验空间信息
     *
     * @param space
     * @param add
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        Integer spaceType = space.getSpaceType();
        // 要创建
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceType == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不能为空");
            }
        }
        // 修改数据时，如果要改空间级别
        if (spaceLevel != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }


    /**
     * 根据空间等级填充空间信息
     *
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    /**
     * 检查空间权限
     *
     * @param space
     * @param loginUser
     */
    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        Long userId = space.getUserId();
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该空间");
        } else if (!loginUser.getId().equals(userId) && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该空间");
        }
    }
}




